package tcpnetwork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    //服务器专属 socket
    private ServerSocket serverSocket;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    //服务器启动代码
    public void start() throws IOException {
        System.out.println("服务器启动...");
        //newCachedThreadPool 不会固定线程数量
        ExecutorService executorService = Executors.newCachedThreadPool();
        while(true) {
            //TCP 是有连接的，要先建立连接
            //获取客户端的连接
            Socket clientSocket = serverSocket.accept();

            //处理本次连接的请求并计算响应
            //使用线程池处理多个客户端的请求
            executorService.submit(() -> {
                try {
                    processCollection(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

    private void processCollection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            // 针对 InputStream 套了一层
            Scanner scanner = new Scanner(inputStream);
            // 针对 OutputStream 套了一层
            PrintWriter writer = new PrintWriter(outputStream);
            while(true) {
                if(!scanner.hasNext()) {
                    System.out.printf("[%s:%d] 客户端下线\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //读取请求
                String request = scanner.next();
                //计算响应
                String response = process(request);
                //发送响应
                writer.println(response);
                //刷新缓存区，内存的响应数据发送出去
                writer.flush();
                //打印日志
                System.out.printf("[%s:%d] request:%s response:%s\n",clientSocket.getInetAddress(),clientSocket.getPort(),
                        request,response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            clientSocket.close();//当客户端下线的时候，记得关闭 socket 资源
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
